// 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
// 输出：7 -> 0 -> 8
// 原因：342 + 465 = 807
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <iostream>

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        ListNode *pHead = new ListNode(0);
        ListNode *p1 = l1, *p2 = l2, *p3 = pHead;
        // ListNode *pNext;
        int jinwei = 0;
        while (p1 != NULL || p2 != NULL)
        {
            //p1,2都没到底
            if (p1 != NULL && p2 != NULL)
            {
                int sum = p1->val + p2->val;
                p1 = p1->next;
                p2 = p2->next;
                p3->next = new ListNode((sum  + jinwei)% 10);
                jinwei = (sum+jinwei) / 10;
                p3 = p3->next;
            }
            // p1到底
            if (p1 == NULL && p2 != NULL)
            {
                p3->next = new ListNode((p2->val+jinwei)%10);
                jinwei = (p2->val+jinwei)/10;
                p2= p2->next;
                p3 = p3->next;
            }
            // p2到底
            if (p1 != NULL && p2 == NULL)
            {
                p3->next = new ListNode((p1->val+jinwei)%10);
                jinwei = (p1->val+jinwei)/10;
                p1= p1->next;
                p3 = p3->next;
            }
        }
        while (jinwei != 0)
        {
            p3->next = new ListNode(jinwei%10);
            jinwei = jinwei/10;
            p3 = p3->next;
        }
        return pHead->next;
    }
};